import * as neDB from 'nedb'
// const neDB = require('nedb')
import { config } from '../config'

const db = new neDB({
  filename: config.neDBDatabase,
})
db.loadDatabase(err => {
  if (err) {
    console.log('NeDB.loadDatabase ERROR ', err)
  }
})

export default class PromisifyNeDB {
  public static insert (doc): Promise<any> {
    return new Promise((resolve, reject) => {
      db.insert(doc, (err, newDoc) => {
        if (err) return reject(err)
        resolve(newDoc)
      })
    })
  }

  /**
   * 根据条件查找数据
   * @param searchOpt 查找数据的格式，Operators ($lt, $lte, $gt, $gte, $in, $nin, $ne, $exists, $regex)
   * 文档查看 https://github.com/louischatriot/nedb/wiki/Finding-documents
   */
  public static find (searchOpt: object): Promise<object[]> {
    return new Promise((resolve, reject) => {
      db.find(searchOpt, (err, docs) => {
        if (err) return reject(err)
        resolve(docs)
      })
    })
  }

  /**
   * 根据条件查找数据
   * @param searchOpt 查找数据的格式，Operators ($lt, $lte, $gt, $gte, $in, $nin, $ne, $exists, $regex)
   * 文档查看 https://github.com/louischatriot/nedb/wiki/Finding-documents
   */
  public static findOne (searchOpt: object): Promise<any> {
    return new Promise((resolve, reject) => {
      db.findOne(searchOpt, (err, doc) => {
        if (err) return reject(err)
        resolve(doc)
      })
    })
  }

  /**
   * 根据条件更新数据 db.update(query, update, options, callback)
   * @param searchOpt 查找数据的格式，Operators ($lt, $lte, $gt, $gte, $in, $nin, $ne, $exists, $regex)
   * 文档查看 https://github.com/louischatriot/nedb/wiki/Updating-documents
   */
  public static update (searchOpt: object, oprationsOrNewDOC: object, options: object = {}): Promise<any> {
    return new Promise((resolve, reject) => {
      db.update(searchOpt, oprationsOrNewDOC, options, (err, doc) => {
        if (err) return reject(err)
        resolve(doc)
      })
    })
  }
  public static upsert (searchOpt: object, oprationsOrNewDOC: object, options: object = {}): Promise<any> {
    return new Promise((resolve, reject) => {
      db.update(
        searchOpt,
        oprationsOrNewDOC,
        {
          upsert: true,
          ...options,
        },
        (err, doc) => {
        if (err) return reject(err)
        resolve(doc)
      })
    })
  }
  public static remove (searchOpt: object, options: object = {}): Promise<any> {
    return new Promise((resolve, reject) => {
      db.remove(searchOpt, options, (err, doc) => {
        if (err) return reject(err)
        resolve(doc)
      })
    })
  }
}

const TOKEN_PREFIX = config.wechatOAuthTokenPrefix
export async function CoWechatOAuthTokenRead(openid) {
  const data = await PromisifyNeDB.findOne({
    type: TOKEN_PREFIX,
    openid,
  })
  return data
}
export async function CoWechatOAuthTokenWrite(openid: string, token: object) {
  const data = await PromisifyNeDB.upsert({
    type: TOKEN_PREFIX,
    openid,
  }, {
    type: TOKEN_PREFIX,
    openid,
    ...token,
  })
  console.log(data)
}
